package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {
@Autowired
private WxMaService wxMaService;
@Autowired
private CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 条件：
     * 1.前端开发者appid与服务器appid一致
     * 2.前端开发者 必须加入开发者
     * @param code
     * @return
     */
    @Transactional(rollbackFor ={ Exception.class})
    @Override
    public Long login(String code) {
        String openId = null;
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
            log.info("【小程序授权】openId={}",openId);
        }catch (Exception e){
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
        }
        CustomerInfo customerInfo = this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getWxOpenId,openId));
        if (null==customerInfo){
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://jiyun-spyx.oss-cn-beijing.aliyuncs.com/2024/22/11/fbb371e03a2c41c8803cb71018168b8d9.jpg");
            customerInfo.setWxOpenId(openId);
            this.save(customerInfo);
        }
//        登录日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);
        return customerInfo.getId();
    }

    @Override
    public CustomerInfo getCustomerLoginInfo(Long customerId) {

        CustomerInfo customerInfo = this.getById(customerId);
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo,customerLoginVo);
//        判断是否绑定手机号码，如果未绑定，小程序端发起绑定事件
        boolean b = StringUtils.hasText(customerInfo.getPhone());
        customerLoginVo.setIsBindPhone(b);
        return customerInfo;
    }
@Autowired
private  CustomerInfoMapper customerInfoMapper;
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        try{
//            调用微信API获取用户的手机号
            WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneInfo.getPhoneNumber();
            log.info("phoneInfo{}", JSON.toJSONString(phoneInfo));
            Long customerId = updateWxPhoneForm.getCustomerId();
            CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
            customerInfo.setPhone(phoneNumber);
            customerInfoMapper.updateById(customerInfo);
            return true;
        }catch (WxErrorException e){
            throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
        }
    }
}
